﻿#region

using System.Linq;
using JsMapper.BO;
using JsMapper.BO.Config;

#endregion

namespace JsMapper.BL
{
    public static class JsOutputBuilder
    {
        public static string ForJsModel(IJsModel model, IJsModelMapper mapper)
        {
            var modelOutput = mapper.GetJs(model);
            var nsOutput = ForJsNamespace(model.JsNamespace);
            var modelObj = string.Format("{0}={1};", model.Name, modelOutput);

            return string.IsNullOrEmpty(model.JsNamespace)
                       ? string.Format("{0} {1}", nsOutput, modelObj)
                       : string.Format("{0} {1}.{2}", nsOutput, model.JsNamespace, modelObj);
        }
        
        public static string ForJsModel(IJsModel model, JsModelConfig config, IJsModelMapper mapper)
        {
            var ns = model.JsNamespace ?? config.JsNamespace;
            var modelOutput = mapper.GetJs(model);
            var nsOutput = ForJsNamespace(ns);
            var modelObj = string.Format("{0}={1};", model.Name, modelOutput);

            return ns == null
                       ? string.Format("{0} {1}", nsOutput, modelObj)
                       : string.Format("{0} {1}.{2}", nsOutput, ns, modelObj);
        }

        public static string ForJsNamespace(string jsNamespace, bool withUndefinedCheck = true)
        {
            var ret = string.Empty;
            if (string.IsNullOrEmpty(jsNamespace)) return ret;

            var allNs = jsNamespace.Split('.');
            for (var curLevel = 1; curLevel <= allNs.Length; curLevel++)
            {
                var curNs = string.Join(".", allNs.Take(curLevel));
                var curNsObj = string.Format("{0} = {{}};", curNs);

                if (withUndefinedCheck)
                    curNsObj = string.Format("if(typeof({0}) === 'undefined') {{ {1} }}", curNs, curNsObj);
                
                ret += curNsObj;
            }

            return ret;
        }
    }
}